chrome.runtime.onInstalled.addListener(() => {
    console.log('SwiftShadow Downloader Extension Installed');
    chrome.contextMenus.create({
        id: "downloadWithSwiftShadow",
        title: "Download with SwiftShadow",
        contexts: ["link", "video", "audio", "image"]
    });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
    if (info.menuItemId === "downloadWithSwiftShadow") {
        let urlToDownload = info.linkUrl || info.srcUrl || info.pageUrl;
        if (urlToDownload) {
            console.log("Context menu download request for: " + urlToDownload);
            chrome.runtime.sendNativeMessage(
                'com.swiftshadow.downloader', // Native messaging host name
                {action: 'download_url', url: urlToDownload},
                response => {
                    if (chrome.runtime.lastError) {
                        console.error('Error sending native message from context menu:', chrome.runtime.lastError.message);
                    } else {
                        console.log('Received response from native app (context menu):', response);
                    }
                }
            );
        }
    }
});

let sniffedResources = [];

chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        // Filter for relevant resource types (e.g., media, documents, XHR)
        const relevantTypes = ["media", "object", "xmlhttprequest", "main_frame", "sub_frame"];
        const subtitleExtensions = [".srt", ".vtt", ".ass", ".ssa", ".smi"];
        const subtitleMimeTypes = ["text/vtt", "application/x-subrip", "text/plain"]; // Common subtitle MIME types

        if (details.url.startsWith("http")) {
            // Check for relevant resource types or subtitle extensions/MIME types
            const isSubtitle = subtitleExtensions.some(ext => details.url.toLowerCase().endsWith(ext)) ||
                (details.responseHeaders && details.responseHeaders.some(header => header.name.toLowerCase() === 'content-type' && subtitleMimeTypes.some(mime => header.value.toLowerCase().includes(mime))));

            if (relevantTypes.includes(details.type) || isSubtitle) {
                sniffedResources.push({
                    url: details.url,
                    type: details.type,
                    method: details.method,
                    tabId: details.tabId,
                    timeStamp: details.timeStamp,
                    isSubtitle: isSubtitle // Mark if it's a subtitle
                });
                console.log("Sniffed resource:", details.url, "Is Subtitle:", isSubtitle);
            }
        }
    },
    {urls: ["<all_urls>"]},
    ["blocking"]
);

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "download_current_page") {
        console.log("Background script received download request for: " + request.url);
        chrome.runtime.sendNativeMessage(
            'com.swiftshadow.downloader', // Native messaging host name
            {action: 'download_url', url: request.url},
            response => {
                if (chrome.runtime.lastError) {
                    console.error('Error sending native message:', chrome.runtime.lastError.message);
                    sendResponse({success: false, message: chrome.runtime.lastError.message});
                } else {
                    console.log('Received response from native app:', response);
                    sendResponse(response);
                }
            }
        );
        return true; // Indicates that sendResponse will be called asynchronously
    } else if (request.action === "download_custom_url") {
        console.log("Background script received custom download request for: " + request.url);
        chrome.runtime.sendNativeMessage(
            'com.swiftshadow.downloader', // Native messaging host name
            {action: 'download_url', url: request.url},
            response => {
                if (chrome.runtime.lastError) {
                    console.error('Error sending native message for custom URL:', chrome.runtime.lastError.message);
                    sendResponse({success: false, message: chrome.runtime.lastError.message});
                } else {
                    console.log('Received response from native app for custom URL:', response);
                    sendResponse(response);
                }
            }
        );
        return true; // Indicates that sendResponse will be called asynchronously
    }
});
if (request.action === "download_resource") {
    console.log("Received download request for resource: " + request.url);
    // Forward to native messaging host
    chrome.runtime.sendNativeMessage(
        'com.swiftshadow.downloader', // Native messaging host name
        {action: 'download_url', url: request.url},
        response => {
            if (chrome.runtime.lastError) {
                console.error('Error sending native message:', chrome.runtime.lastError.message);
            } else {
                console.log('Received response from native app:', response);
            }
        }
    );
} else if (request.action === "get_sniffed_resources") {
    const subtitleResources = sniffedResources.filter(resource => resource.isSubtitle);
    sendResponse({resources: subtitleResources});
    sniffedResources = []; // Clear resources after sending to popup
} else if (request.action === 'download_subtitle') {
    const subtitleUrl = request.url;
    if (subtitleUrl) {
        chrome.downloads.download({url: subtitleUrl, conflictAction: 'uniquify'}, (downloadId) => {
            if (chrome.runtime.lastError) {
                console.error('Subtitle download error:', chrome.runtime.lastError.message);
                sendResponse({success: false, error: chrome.runtime.lastError.message});
            } else {
                console.log('Subtitle download started with ID:', downloadId);
                sendResponse({success: true, downloadId: downloadId});
            }
        });
        return true; // Indicate that sendResponse will be called asynchronously
    } else {
        sendResponse({success: false, error: 'No subtitle URL provided.'});
    }
}
})
;